package com.hui.platform.falseworkapi.common.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统一日志处理切面（主要监听接口数据）
 */

@Aspect // 切面声明
@Component // 组件
@Order(1) // 切面优先级
public class WebLogAspect {

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    /**
     * 开始时间记录器（每个线程保存一份）
     */
    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * AOP切入点
     */
    @Pointcut("execution(* com.hui.platform.falseworkapi.service.business.*.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * 切入点之前
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
    }

    /**
     * 切入点返回结果之后
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /**
     * 切入点执行之后，未返回结果之前
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 声明记录结果集合
        Map<String, Object> logMap = new LinkedHashMap<>();
        // 返回结果集合
        Object result = joinPoint.proceed();
        // 记录结束时间
        long endTime = System.currentTimeMillis();
        // 通过签名获取被截取的Method（反射）
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        // 获取方法注解，如果为Swagger方法注解，则记录信息
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            // 记录Api接口信息
            logMap.put("description", log.value());
        }
        // 设置请求基础路径
        logMap.put("basePath", getBasePath(request));
        // 设置请求IP地址
        logMap.put("ip", request.getRemoteHost());
        // 设置请求方法，GET，POST...
        logMap.put("method", request.getMethod());
        // 设置请求参数
        logMap.put("parameter", getParameters(joinPoint.getArgs()));
        // 设置结果截取方法返回的结果
        logMap.put("result", result);
        // 设置响应的时间
        logMap.put("spendTime", (int) (endTime - startTime.get()));
        // 设置开始的时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatStartTime = simpleDateFormat.format(new Date(startTime.get()));
        logMap.put("startTime", formatStartTime);
        // 设置URI
        logMap.put("uri", request.getRequestURI());
        // 设置URL
        logMap.put("url", request.getRequestURL().toString());

        // 输出日志信息(打开注释可以获取为空的字段）
        try {
        	String logMapString = JSON.toJSONString(logMap, SerializerFeature.PrettyFormat  ,SerializerFeature.WriteMapNullValue );
        	logger.debug(logMapString);
		} catch (Exception e) {
			logger.warn("Json Format Exception:"+e.getMessage());
		}
        return result;
    }

    /**
     * 获取请求basePath
     * @param request
     * @return
     */
    public String getBasePath(HttpServletRequest request) {
        StringBuffer basePath = new StringBuffer();
        String scheme = request.getScheme();
        String domain = request.getServerName();
        int port = request.getServerPort();
        basePath.append(scheme);
        basePath.append("://");
        basePath.append(domain);
        if ("http".equalsIgnoreCase(scheme) && 80 != port) {
            basePath.append(":").append(String.valueOf(port));
        } else if ("https".equalsIgnoreCase(scheme) && 443 != port) {
            basePath.append(":").append(String.valueOf(port));
        }
        return basePath.toString();
    }

    /**
     * 过滤相关参数
     * @param params
     * @return
     */
    private List<?> getParameters(Object[] params) {
        return Arrays.asList(params)
                .stream().filter(param -> param instanceof HttpServletRequest ? false : true)
                .collect(Collectors.toList());
    }

}
